#include "track/id_generator.h"

#include <algorithm>
#include <array>
#include <cstdint>
#include <vector>

IdGenerator::IdGenerator() noexcept : is_id_used_{false} {}

void IdGenerator::Init() noexcept {
  is_id_used_.at(0) = true;
  for (std::uint16_t i{1U}; i <= 255U; ++i) {
    id_queue_.emplace_back(static_cast<std::uint8_t>(i));
    is_id_used_.at(i) = false;
  }
}

std::uint8_t IdGenerator::GetId() noexcept(false) {
  mutex_.lock();
  if (id_queue_.empty()) {
    // throw OutOfResourceException("No id available");
  }
  std::uint8_t id{id_queue_.front()};
  is_id_used_.at(id) = true;
  id_queue_.pop_front();
  mutex_.unlock();
  return id;
}

bool IdGenerator::IsIdUsed(std::uint8_t id) const noexcept {
  return is_id_used_.at(id);
}

void IdGenerator::ReleaseId(std::uint8_t id) noexcept {
  mutex_.lock();
  if (id > 0 && is_id_used_.at(id)) {
    id_queue_.emplace_back(id);
    is_id_used_.at(id) = false;
  }
  mutex_.unlock();
}

/* vim: set ts=2 sw=2 sts=2 tw=100 et: */
